import keyCodes from '@/static/json/keyCode.json'; // 请确保路径正确

// 权限ID数组
const permissionIDs = [
	'android.permission.READ_EXTERNAL_STORAGE',
	'android.permission.WRITE_EXTERNAL_STORAGE'
	// 在此添加更多需要的权限
];

const requestPermission = (permissionID) => {
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			[permissionID],
			function(resultObj) {
				var result = 0;
				for (var i = 0; i < resultObj.granted.length; i++) {
					var grantedPermission = resultObj.granted[i];
					console.log('已获取的权限：' + grantedPermission);
					result = 1;
				}
				for (var i = 0; i < resultObj.deniedPresent.length; i++) {
					var deniedPresentPermission = resultObj.deniedPresent[i];
					console.log('拒绝本次申请的权限：' + deniedPresentPermission);
					result = 0;
				}
				for (var i = 0; i < resultObj.deniedAlways.length; i++) {
					var deniedAlwaysPermission = resultObj.deniedAlways[i];
					console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
					result = -1;
				}
				resolve(result);
			},
			function(error) {
				console.log('申请权限错误：' + error.code + ' = ' + error.message);
				reject(error);
			}
		);
	});
};

async function requestPermissions(permissionIDs) {
	// 不要同时授权多个权限，否则可能会被安卓系统认定为恶意应用，直接永久拒绝所有申请。
	for (let i = 0; i < permissionIDs.length; i++) {
		let permissionID = permissionIDs[i];
		let result = await requestPermission(permissionID);
		if (result !== 1) {
			throw new Error(permissionID + '未获得授权或被永久拒绝权限');
		}
	}
}

async function initController() {
	const _init1 = () => {
		return new Promise((resolve) => {
			const Controller = uni.requireNativePlugin('rfidsdk_ModuleController');
			Controller.initController((data) => {
				console.error('initPda: ' + JSON.stringify(data));
				resolve();
			});
		});
	};
	return Promise.all([_init1()]);
}

/**
 * 初始化PDA方法入口
 * @public
 */
async function initializeApp() {
	try {
		// 请求权限
		await requestPermissions(permissionIDs);

		// 初始化PDA
		uni.showLoading({
			title: '正在初始化设备',
			mask: true
		});

		await initController();
	} catch (error) {
		console.error('Initialization failed:', error);
	}
}



export default initializeApp;